<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <pageTools>
          <template #left>
            <span>总共{{ total }}条</span>
          </template>
          <template #right>
            <el-button type="warning" @click="$router.push({
              path: '/employees/import',
            })" v-allow="'import_excel'">导入Excel</el-button>
            <el-button v-allow="'export_excel'" type="danger" @click="hExport">导出Excel</el-button>
            <el-button type="primary" @click="showDialog = true">新增角色</el-button>
          </template>
        </pageTools>
      </el-card>

      <el-card style="margin-top:20px">
        <el-table border :data="employees" style="width: 100%;height:100%">
          <el-table-column type="index" label="序号" width="width">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="头像" width="width">
            <template v-slot="scope">
              <img :src="scope.row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" width="width">
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式" width="width">
            <template v-slot="scope">
              <span>{{ formatEmployeement(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" width="width">
          </el-table-column>
          <el-table-column label="入职时间" width="width" sortable>
            <template v-slot="scope">
              <span>{{ formatDate(scope.row.timeOfEntry) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template v-slot='scope'>
              <el-button type="text" @click="$router.push({
                name: 'detail',
                params: { id: scope.row.id }

              })">查看</el-button>
              <el-button type="text" @click="hAssign(scope.row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(scope.row.id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <div style=" margin-top: 10px">
          <el-pagination @size-change="hSizeChange" @current-change="hCurrentChange" :current-page="q.page"
            :page-sizes="[5, 10, 20]" :page-size="q.size" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-card>
    </div>
    <el-dialog title="新增员工" :visible.sync="showDialog" width="50%" :close-on-click-modal="false"
      :close-on-press-escape="false" @closed="hClosed">
      <emp-dialog ref="addEmpForm" @close="showDialog = false" @success="hSuccess"></emp-dialog>
    </el-dialog>
    <el-dialog title="新增员工" :visible.sync="showDialogRole" width="50%" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <assign-role v-if="showDialogRole" :id="curId" @close="showDialogRole = false"></assign-role>
    </el-dialog>
  </div>
</template>

<script>
import { delEmployee, getEmployees } from '@/api/employees';
import employeesConst from '@/constant/employees'
import empDialog from './empDialog.vue';
import dayjs from 'dayjs';
import assignRole from './assignRole.vue';

export default {
  components: {
    empDialog,
    assignRole
  },
  data() {
    return {
      employees: [],
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }

  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      try {
        const res = await getEmployees(this.q)
        console.log(res);
        this.employees = res.data.rows
        this.total = res.data.total
      }
      catch (e) {
        console.log(e);
      }
    },
    formatEmployeement(code) {
      const result = employeesConst.hireType.find(item => item.id == code)
      // 如果result.value数字异常
      if (result) {
        return result.value
      } else {
        return '未知'
      }
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hCurrentChange(page) {
      this.q.page = page
      this.loadEmployees(this.q)
    },
    hSizeChange(size) {
      this.q.size = size
      this.loadEmployees(this.q)
    },
    async hDel(id) {

      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await delEmployee(id)
          this.$message({
            type: 'success',
            message: res.message
          });
          // 判断当前页数据是否最后一条，且当前页>1,当前页-1
          if (this.employees.length === 1 && this.q.page > 1) {
            this.q.page--
          }
          this.loadEmployees()
        } catch (error) {
          this.$message({
            type: 'error',
            message: error.message
          });
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    hSuccess() {
      this.showDialog = false
      if (this.total % this.q.size == 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    hClosed() {
      console.log('this.$refs.addf', this.$refs.addEmpForm);
      this.$refs.addEmpForm.resetForm()
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getEmployees({
        page: 1,
        size: this.total
      })
      const excel = await import('@/vendor/Export2Excel')
      const list = res.data.rows
      console.log(list);

      const zhList = list.map(item => {
        const zhObj = {}
        const enKeys = Object.keys(item)//['id', 'mobile', 'username', 'password']
        enKeys.forEach(enKey => {
          const zhKey = mapInfo[enKey]
          zhObj[zhKey] = item[enKey]
        });
        return zhObj
      });
      console.log('zhList', zhList);

      // const zhList = list.map(({ id, password, mobile, username, timeOfEntry, formOfEmployment, correctionTime, workNumber, departmentName, staffPhoto }) => {
      //   return {
      //     编号: id,
      //     手机号: mobile,
      //     姓名: username,
      //     密码: password,
      //     入职日期: timeOfEntry,
      //     聘用形式: formOfEmployment,
      //     工号: workNumber,
      //     转正日期: correctionTime,
      //     部门: departmentName,
      //     头像: staffPhoto
      //   }
      // })


      const tHeader = Object.keys(zhList[0])
      const data = list.map(item => {
        item.formOfEmployment = item.formOfEmployment == 1 ? '正式' : '非正式'
        return Object.values(item)
      });
      console.log(data);
      excel.export_json_to_excel({
        header: tHeader,
        data,
        filename: 'emplpyees',
        autoWidth: true,
        bookType: 'xlsx'
      })

    },
    hAssign(id) {
      this.showDialogRole = true
      this.curId = id
    }

  }
}
</script>
<style scoped lang="scss">
.el-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>